<?php

namespace Application\controller;

use Application\model\BaseLoginModel;
use Application\model\GiftModel;
use DateTime;

class ServerSideController extends BaseLoginController
{
    private $sd = '';
    private $ed = '';
    /**
     * 登录上报玩家信息
     * @return void
     */
    public function ReportActor()
    {
        $cpid = $this->get('channel');
        $openid = $this->get('openId');
        $sid = $this->get('sid');
        $actorId = $this->get('actorId');
        $actorName = $this->get('actorName');
        $createTime = $this->get('createTime',0);
        // 先打一个log
        logfile('ServerSideModel', "cpid:$cpid openid:$openid sid:$sid actorId:$actorId actorName:$actorName");
        // 数据合法性
        if (empty($actorId) || empty($actorName)) { $this->error('actor id or name empty'); }
        if (empty($sid)) { $this->error('sid is empty'); }

        $data['open_id'] = $openid;
        $data['sid'] = $sid;
        $data['last_cid'] = CID;//更新渠道
        $data['actor_id'] = $actorId;
        $data['actor_name'] = $actorName;
        $data['create_cpid'] = $cpid;
        $data['create_time'] = date('Y-m-d H:i:s',$createTime ? $createTime / 1000 : time());

        /* @var $AccountModel \Application\model\AccountModel */
        $AccountModel = $this->model('Account');
        list($account,$res) = $AccountModel->insertOrUpdateActor($data);
        $logs = ['login_dt'=>date('Y-m-d H:i:s'),'cid'=>CID,'cpid'=>GAME_ID,'ccid'=>CHANNEL_ID] + $data;

        //兼容数据,is_new 等数据无效了
        $default = ['account' => $openid];
        $AccountModel->redis->lpush('report_actor_dau', http_build_query($logs + ($account ?: $default)));
        if ($res) {
            $this->success([]);
        }
        if (!$account) {
            logfile('ServerSideModel',"account not find===$openid::$actorId");
            //$this->success([]);
            $this->error('account not find');
        }
        $this->error('update or insert error');
    }

    /**
     * 上报场景
     * @return void
     */
    public function reportScene()
    {
        $openid = $this->get('openId');
        $actorId = $this->get('actorId');
        $sid = $this->get('sid');
        $scene = $this->get('scene');
        $AccountModel = $this->model('Account');
        logfile('ServerSideModel', "reportScene: openid:$openid sid:$sid actorId:$actorId scene:$scene");

        //$account = $AccountModel->getAccountInfo($openid);
        $account = $AccountModel->getAccountInfo($openid,$sid,$actorId);
        if ($account) {
            $id = $account['id'];
            // 修改角色名数据
            /*if ($account['actor_id'] != $actorId || $account['sid'] != $sid) {
                $this->error('actor invalid');
            }*/
            $res = $AccountModel->updateActorById($id, ['scene'=>$scene]);
            if ($res){
                $this->success([]);
            }
            logfile('ServerSideModel', "reportScene: actorId:$actorId scene:$scene update error");
            $this->error("actorId:$actorId scene:$scene update error");
        }
        logfile('ServerSideModel', "reportScene: account:$openid empty");
        $this->error("reportScene: account:$openid empty");

    }
    
    /**
     * 更新玩家信息
     * @return void
     */
    public function updateActor()
    {
        $platform = $this->get('platform');
        $openid = $this->get('openId');
        $sid = $this->get('sid');
        $actorId = $this->get('actorId');
        $actorName = $this->get('actorName');
        // 先打一个log

        // 数据合法性
        if (empty($actorId) || empty($actorName)) { $this->error('actor id or name empty'); }
        $data['actor_id'] = $actorId;
        $data['sid'] = $sid;
        $data['actor_name'] = $actorName;
        $AccountModel = $this->model('Account');
        $account = $AccountModel->getAccountInfo($openid);
        if ($account) {
            $id = $account['id'];
            // 修改角色名数据
            if ($account['actor_id']) unset($data['actor_id']);
            if ($account['sid']) unset($data['sid']);

            $res = $AccountModel->updateActorById($id, $data);
            if ($res){
                $this->success([]);
            } else {
                // 失败打log
                // TODO
            }
        }
        $this->error('update error');

    }

    /**
     * 封号
     * @return void
     */
    public function banAccount()
    {
        $platform = $this->get('platform');
        $openid = $this->get('openId');
        $time = $this->get('time');
        // 数据合法性
        if (empty($openid)) { $this->error('open id empty'); }
        $Account = $this->model('Account');
        $res = $Account->updateStatusByAccount($openid);
        if ($res) {
            // 插入到log表
            $Account->db('_backdb')->insert(['type'=>2, 'status'=>1, 'account'=>$openid, 'ban_dt'=>date('Y-m-d H:i:s'), 'ban_time'=>round($time/60), 'ban_user'=>'系统', 'remark'=>'言论监控'], 'gm_ban');
            $this->success([]);
        }
        $this->error('ban account error');
    }

    /**
     * 使用礼包码
     * @return void
     */
    public function usedGitCode()
    {
        $platform = $this->get('platform');
        $code = $this->get('code');
        $actorId = $this->get('playerId');
        $name = $this->get('name');
        $level = $this->get('level');
        $vip = $this->get('vip');
        $amount = $this->get('amount');

        $Gift = $this->model('Gift');
        if ($code===null || $actorId===null || $name===null || $level===null || $vip===null || $amount===null)
        {
            $Gift->logfile("参数错误 code:$code actorId:$actorId name:$name level:$level vip:$vip amount:$amount");
            $this->backError('礼包异常', 13008);
        }

        // 通过礼包码查询礼包信息和配置信息
        $codeInfo = $Gift->getGiftCodeInfoByCode($code);
        if (empty($codeInfo)) {
            $Gift->logfile("礼包码不存在 code:$code");
            $this->backError('礼包码不存在', 13004);
        }

        if ($codeInfo['used_times'] >= $codeInfo['times'])
        {
            $Gift->logfile("此礼包码已被使用 code:$code used:{$codeInfo['used_times']} times:{$codeInfo['times']}");
            $this->backError('礼包码已使用', 13005);
        }

        // 通过批次ID获取礼包配置数据
        $configInfo = $Gift->getGiftCodeConfigInfoById($codeInfo['config_id']);
        if (empty($configInfo))
        {
            $Gift->logfile("礼包批次异常 code:$code config_id:{$codeInfo['config_id']}");
            $this->backError('礼包批次异常', 13006);
        }

        if ($configInfo['cid'] != '' && $configInfo['cid'] != strtolower($platform))
        {
            $Gift->logfile("此礼包码不支持该渠道 code:$code cid:{$configInfo['cid']} platform:$platform");
            $this->backError('礼包码不支持该渠道', 13007);
        }

        // 通过礼包id获取礼包信息
        $giftInfo = $Gift->getGiftInfoById($codeInfo['gift_id']);
        if (empty($giftInfo)) {
            $Gift->logfile("礼包异常 code:$code gift_id:{$codeInfo['gift_id']}");
            $this->backError('礼包异常', 13008);
        }
        // 判断有效期
        if (strtotime($giftInfo['start_dt']) >time() || strtotime($giftInfo['end_dt']) < time()) {
            $Gift->logfile("礼包已过期 code:$code start:{$giftInfo['start_dt']} end:{$giftInfo['end_dt']}");
            $this->backError('礼包已过期', 13009);
        }

        if ($giftInfo['used_num'] >= $giftInfo['num'])
        {
            $Gift->logfile("此礼包已被使用 code:$code used:{$giftInfo['used_num']} num:{$giftInfo['num']}");
            $this->backError('礼包码已使用', 13005);
        }

        // 通过玩家角色ID获取玩家领取的记录
        $giftLogs = $Gift->getGiftCodeLogInfoByActorId($actorId);
        if ($giftLogs) {
            $this->getGiftDate($giftInfo['days'], $giftInfo['start_dt']);
            $giftTimes = $giftDaysTime = 0;
            foreach ($giftLogs as $log) {
                if ($log['gift_id'] == $giftInfo['id']) {
                    $giftTimes++;
                    if ($giftInfo['days'] !== '0') {
                        if ($this->sd <= $log['create_dt'] && $this->ed >= $log['create_dt']) {
                            $giftDaysTime++;
                        }
                    }
                }
            }

            if ($giftTimes >= $giftInfo['times'] && $giftInfo['days'] === '0')
            {
                $Gift->logfile("此礼包您已领取过{$giftTimes}次 code:$code giftTimes:$giftTimes times:{$giftInfo['times']}");
                $this->backError('礼包领取次数已达上限', 13010);
            }

            if ($giftDaysTime >= $giftInfo['times']) {
                $Gift->logfile("此礼包您已领取 code:$code 周期时间:{$this->sd}-{$this->ed} giftDaysTime:$giftDaysTime times:{$giftInfo['times']}");
                $this->backError('礼包码已使用', 13005);
            }
        }

        // 插入使用日志log表
        $row = [];
        $row['code'] = $code;
        $row['gift_id'] = $giftInfo['id'];
        $row['items'] = $giftInfo['items'];
        $row['gift_name'] = $giftInfo['name'];
        $row['items_str'] = $giftInfo['items_str'];
        $row['config_id'] = $configInfo['id'];
        $row['type'] = $configInfo['type'];
        $row['actor_id'] = $actorId;
        $row['actor_name'] = $name;
        $row['level'] = $level;
        $row['vip'] = $vip;
        $row['amount'] = $amount;
        $row['create_dt'] = date('Y-m-d H:i:s');
        $res = $Gift->insertGiftCodeLog($row);

        if ($res) {
            // 更新各个配置表已使用次数
            $res = $Gift->updateGift($row);
            if ($res) {
                $this->success([]);
            } else {
                // 删除log数据
                $Gift->delGiftCodeLog(['code'=>$code]);
                $Gift->logfile("修改gift配置表失败 code:$code");
                $this->backError('领取失败，请联系客服', 13011);
            }
        } else {
            $Gift->logfile("插入gift code log表失败 code:$code");
            $this->backError('领取失败，请联系客服', 13011);
        }
    }

    /**
     * 获取礼包有效期时间段
     * @param $days
     * @param $startDt
     */
    public function getGiftDate($days, $startDt)
    {
        $startDate = date("Y-m-d", strtotime($startDt));
        $endDate = date('Y-m-d', strtotime($startDate . ' +' . ($days-1) . ' days'));
        $reSDate = date('Y-m-d', strtotime($startDate . ' +' . $days . ' days'));
        $this->sd = $startDate;
        $this->ed = $endDate.' 23:59:59';
        if ($endDate < date("Y-m-d") && $days !== '0') {
            $this->getGiftDate($days, $reSDate);
        }
    }


}